Page({
  data: {
    list: [
      {
        index: 0,
        x: 0,
        y: 0,
      },
      {
        index: 1,
        x: 0,
        y: 0,
      },
      {
        index: 2,
        x: 0,
        y: 0,
      },
      {
        index: 3,
        x: 0,
        y: 0,
      },
      {
        index: 4,
        x: 0,
        y: 0,
      },
      {
        index: 5,
        x: 0,
        y: 0,
      },
      {
        index: 6,
        x: 0,
        y: 0,
      },
    ],
    moveList: [
      {
        index: 0,
        x: 0,
        y: 0,
      },
      {
        index: 1,
        x: 0,
        y: 0,
      },
      {
        index: 2,
        x: 0,
        y: 0,
      },
      {
        index: 3,
        x: 0,
        y: 0,
      },
      {
        index: 4,
        x: 0,
        y: 0,
      },
      {
        index: 5,
        x: 0,
        y: 0,
      },
      {
        index: 6,
        x: 0,
        y: 0,
      },
    ],
    curX: 0,
    curY: 0,
    isMove: false,
    boxList: [],
    moveIndex: -1,
    intersectIndex: 0,
    columns: 3,
  },

  onLoad() {
    // this.getPosition2();
    this.init();
  },

  init() {
    // this.getMoveDomInfo();
    const query = wx.createSelectorQuery();
    query.selectAll(".box").boundingClientRect();
    query.select(".page").boundingClientRect();
    query.selectViewport().scrollOffset();
    query.exec((res) => {
      let cols = 1;
      let lastTop = 0;
      let lastLeft = 0;
      let transformX = 0;
      let transformY = 0;
      res[0].forEach((item, index) => {
        if (index !== 0) {
          if (item.top !== lastTop) {
            cols += 1;
          }
          if (transformX === 0) {
            transformX = item.left - lastLeft;
          }
          if (transformY === 0) {
            transformY = item.top - lastTop;
          }
        }

        lastLeft = item.left;
        lastTop = item.top;
      });
      const rows = Math.floor(res[0].length / cols);
      this.moveParent = res[1];
      this.moveChild = {
        width: this.moveParent.width / cols,
        height: this.moveParent.height / rows,
      };
      this.moveParent.top += res[2].scrollTop;
      this.data.columns = cols;
      this.transformY = transformY;
      this.transformX = transformX;
      this.setListPosition();
      console.log(this.moveChild, this.moveParent, transformY, transformX);
    });
  },

  setListPosition() {
    // const { list, columns } = this.data
    // list.forEach((item, index) => {
    //   item.lessX = -this.transformX
    //   item.overX = this.transformX
    //   if (index % columns === 0) {
    //     item.lessX = -this.transformX * 2
    //     item.overX =
    //   }
    // })
  },

  getMoveDomInfo() {
    const query = wx.createSelectorQuery();
    query.select(".box").boundingClientRect();
    query.exec((res) => {
      let cols = 1;
      res[0].forEach((item) => {
        if (item.top !== lastTop) {
          cols += 1;
        }
        lastTop = item.top;
      });
    });
  },

  getPosition() {
    const query = wx.createSelectorQuery();
    query.selectAll(".box").boundingClientRect();
    query.exec((res) => {
      let listPosition = {};
      let firstTop;
      let firstLeft;
      let lastOverX = 0;
      let lastOverY = 0;
      let lastTop = 0;
      let lastLeft = 0;
      res[0].forEach((item, index) => {
        const { left, top, width, height } = item;
        const transformX = firstLeft ? left - firstLeft : 0;
        const transformY = firstTop ? top - firstTop : 0;
        if (top !== lastTop) {
          lastOverX = 0;
        }
        if (left !== lastLeft) {
          lastOverY = 0;
        }
        const obj = {
          x: transformX,
          y: transformY,
          overX: transformX === 0 ? 0 : transformX - width / 2 + lastOverX,
          overY: transformY === 0 ? 0 : transformY - height / 2 + lastOverY,
        };
        if (index === 0) {
          firstLeft = left;
          firstTop = top;
        }

        lastOverX = obj.overX;
        lastOverY = obj.overY;
        lastTop = top;
        lastLeft = left;
        listPosition[index] = obj;
      });
      this.listPosition = listPosition;
      console.log("res", res);
      console.log("listPosition", listPosition);
    });
  },

  getPosition2() {
    // const query = wx.createSelectorQuery();
    // query.selectAll(".box").boundingClientRect();
    // query.exec((res) => {
    //   console.log("res", res);
    //   let positionList = [];
    //   let firstLeft = 0;
    //   let firstTop = 0;
    //   res[0].forEach((item, index) => {
    //     const { left, width, top, height } = item;
    //     const centerX = firstLeft ? width / 2 + (left - firstLeft) : width / 2;
    //     const centerY = firstTop ? height / 2 + (top - firstTop) : height / 2;
    //     if (index === 0) {
    //       firstLeft = left;
    //       firstTop = top;
    //     }
    //     positionList.push({
    //       centerX,
    //       centerY,
    //       width,
    //       height,
    //     });
    //   });
    //   let lastCenterX = positionList[0].centerX;
    //   let lastCenterY = positionList[0].centerY;
    //   let row = 1;
    //   let col = 1;
    //   let rowMap = {
    //     [lastCenterX]: row,
    //   };
    //   positionList.forEach((item) => {
    //     const { centerX, centerY } = item;
    //     if (lastCenterY !== centerY) {
    //       col += 1;
    //     }
    //     const beforeRow = rowMap[centerX];
    //     if (beforeRow) {
    //       row = beforeRow;
    //     } else {
    //       rowMap[centerY] = row;
    //       row = row + 1;
    //     }
    //     lastCenterX = centerX;
    //     lastCenterY = centerY;
    //     item.col = col;
    //     item.row = row;
    //   });
    //   this.positionList = positionList;
    //   this.transformX = positionList[1].centerX - positionList[0].centerX;
    //   this.transformY = positionList[1].centerY - positionList[0].centerY;
    //   console.log("positionList", positionList);
    // });
    // 获取每一项的宽高等属性
    this.createSelectorQuery()
      .select(".box")
      .boundingClientRect((res) => {
        this.item = res;

        let query = wx.createSelectorQuery().in(this);
        query.select(".page").boundingClientRect((res) => {
          this.itemWrap = res;
          console.log("item", this.item, this.itemWrap);
        });
        // 需要的是“距离文档流顶部的距离”。所以咱们需要这片区域已经在页面上滚动了多少了，把这个值加上
        if (this.properties.scrollOffset) {
          this.itemWrap.top += this.properties.scrollOffset;
        } else {
          query.selectViewport().scrollOffset((res) => {
            let _wrap = this.itemWrap.top + res.scrollTop;
            this.itemWrap.top = _wrap;
          });
        }
        query.exec();
      })
      .exec();
  },

  bindLongTap(e) {
    const { index } = e.currentTarget.dataset;
    console.log("moveIndex", index);
    this.setData({ moveIndex: index });
    wx.vibrateShort();
  },

  bindTouchStart(e) {
    const { clientX, clientY } = e.touches[0];
    this.startX = clientX;
    this.startY = clientY;
    if (this.data.columns === 1) {
      // 单列时候X轴初始不做位移
      this.tranX = 0;
    } else {
      // 多列的时候计算X轴初始位移, 使 item 水平中心移动到点击处
      this.tranX =
        this.startX - this.moveChild.width / 2 - this.moveParent.left;
    }
    // 计算Y轴初始位移, 使 item 垂直中心移动到点击处
    this.tranY = this.startY - this.moveChild.height / 2 - this.moveParent.top;
  },

  bindTouchMove(e) {
    const { clientX, clientY } = e.touches[0];
    const disX = clientX - this.startX;
    const disY = clientY - this.startY;
    const { moveIndex } = this.data;
    const updateKeyX = `list[${moveIndex}].x`;
    const updateKeyY = `list[${moveIndex}].y`;
    // // this.getIntersectKey(disX, disY);
    // this.getBumpKey(disX, disY);
    this.setData({ [updateKeyX]: disX, [updateKeyY]: disY });
    let tranX = e.touches[0].pageX - this.startX + this.tranX,
      tranY = e.touches[0].pageY - this.startY + this.tranY;

    // let originKey = e.currentTarget.dataset.key;
    this.originKey = this.data.moveIndex;

    let endKey = this.calculateMoving(tranX, tranY);
    console.log('endKey',endKey)

    // 防止拖拽过程中发生乱序问题
    // if (this.originKey == endKey || this.endKey == endKey) return;

    // this.endKey = endKey;
    // this.insert(this.originKey, endKey);
  },

  insert(origin, end) {
    if (origin > end) {
      // this.data.list.forEach((item, index) => {
      //   if (index >= end) {
      //     item.x = -this.transformX;
      //     if (index + (1 % this.data.columns) === 0) {
      //       item.x = -this.transformX * this.data.columns;
      //       item.y = -this.transformY;
      //     }
      //   } else {
      //     item.x = 0;
      //     item.y = 0;
      //   }
      // });
    } else {
      this.data.moveList.forEach((item, index) => {
        if (index > origin) {
          if (index <= end) {
            item.x = -this.transformX;
            if (index % this.data.columns === 0) {
              item.x = this.transformX * (this.data.columns - 1);
              item.y = -this.transformY;
            }
          } else {
            item.x = 0;
            item.y = 0;
          }
        }
      });
    }
    this.setData({ moveList: this.data.moveList });
    console.log("insert", origin, end);
  },

  getBumpKey(disX, disY) {
    const { moveIndex } = this.data;
    const moveCenterX = this.positionList[moveIndex].centerX;
    const moveCenterY = this.positionList[moveIndex].centerY;
    let bumpRow;
    let bumpCol;
    let bumpIndex = moveIndex;
    const moveX = moveCenterX + disX;
    const moveY = moveCenterY + disY;
    for (let index = this.positionList.length - 1; index > 0; index--) {
      const { centerX, centerY, col, row, width, height } =
        this.positionList[index];
      if (disX > 0 && disY > 0) {
        // 右下方向
        if (
          moveX > centerX - width / 2 &&
          moveY >= centerY - height / 2 &&
          index !== moveIndex &&
          col === 1
        ) {
          bumpIndex = index;
          break;
        }
      } else if (disX > 0 && disY < 0) {
        // 右上方向
        if (moveX > centerX / 2 && moveY <= centerY / 2) {
          bumpIndex = index;
          break;
        }
      } else if (disX < 0 && disY > 0 && index !== moveIndex) {
        // 左下方向
        if (moveX < centerX && moveY >= centerY) {
          bumpIndex = index;
          break;
        }
      } else if (disX < 0 && disY < 0 && index !== moveIndex) {
        // 左上方向
        if (moveX < centerX && moveY <= centerY) {
          bumpIndex = index;
          break;
        }
      }
    }
    this.setTransformList(bumpIndex);
    console.log("bumpIndex", bumpIndex);
  },

  getIntersectKey(disX, disY) {
    const { listPosition } = this;
    const { moveIndex } = this.data;
    const { overY: curOverY, overX: curOverX } = listPosition[moveIndex];
    const keys = Object.keys(listPosition).reverse();
    let intersectIndex = 0;
    const compareDisX = disX > 0 ? disX : 0;
    const compareDisY = disY > 0 ? disY : 0;
    for (let i = 0; i < keys.length; i++) {
      const key = keys[i];
      const { overX, overY } = listPosition[key];
      if (compareDisX >= overX && compareDisY >= overY) {
        intersectIndex = key;
        break;
      }
    }
    this.data.intersectIndex = Number(intersectIndex) + moveIndex;
    this.setTransformList();
    console.log("intersectIndex", this.data.intersectIndex);
  },

  setTransformList(index) {
    if (index === 1) {
      const { list } = this.data;
      list[1].x = -this.transformX;
      this.setData({ list });
    }
  },

  bindTouchEnd() {
    const { moveIndex, intersectIndex, list } = this.data;
    if (
      moveIndex < 0 ||
      intersectIndex < 0 ||
      moveIndex >= list.length ||
      intersectIndex >= list.length
    ) {
      return;
    }
    const temp = list[moveIndex];
    list[moveIndex] = list[intersectIndex];
    list[intersectIndex] = temp;
    list.forEach((item) => {
      item.x = 0;
      item.y = 0;
    });
    this.setData({ list }, () => {
      //   this.getPosition();
    });
  },

  calculateMoving(tranX, tranY) {
    let rows = Math.ceil(this.data.list.length / this.data.columns) - 1,
      i = Math.round(tranX / this.moveChild.width),
      j = Math.round(tranY / this.moveChild.height);
    i = i > this.data.columns - 1 ? this.data.columns - 1 : i;
    i = i < 0 ? 0 : i;

    j = j < 0 ? 0 : j;
    j = j > rows ? rows : j;

    let endKey = i + this.data.columns * j;

    endKey =
      endKey >= this.data.list.length ? this.data.list.length - 1 : endKey;
    // console.log({
    //   tranX,
    //   tranY,
    //   i,
    //   j,
    //   columns: this.data.columns,
    //   rows,
    //   endKey,
    // });
    return endKey;
  },
});
